//
//  FGTabBarView.swift
//  FGApp
//
//  Created by ryan on 2019/4/28.
//  Copyright © 2019 ryan. All rights reserved.
//

import UIKit

/// 点击代理协议
protocol FGTabBarDelegate {
    func didSelectItem(itemIndex : Int)
    func didSelectMid()
}


class FGTabBarView: UIView {

    var delegate : FGTabBarDelegate?
    
    var itemArray : [FGTabBarItem] = []
    
    
    
    func addObserves() {
       
    }
    
    init(frame: CGRect, tabBarConfigArr : [Dictionary <String ,String>]) {
        super.init(frame: frame)
        addObserves()
        self.backgroundColor = UIColor.hex(hexString: "#FFFFFF")
        let itemWidth = KScreenWidth / CGFloat(tabBarConfigArr.count)
        for i in 0..<tabBarConfigArr.count {
            let itemDic = tabBarConfigArr[i]
            let itemFrame = CGRect (x: itemWidth * CGFloat(i), y: 0, width: itemWidth, height: frame.size.height)
            // 创建item视图
            let itemView = FGTabBarItem(frame: itemFrame, itemDic: itemDic, itemIndex: i)
            self.addSubview(itemView)
            self.itemArray.append(itemView)
            
            itemView.tag = i
//            if i == 2 {
//                itemView.addTarget(self, action: #selector(self.didClickMid(item:)), for: .touchUpInside)
//            }else {
                itemView.addTarget(self, action: #selector(self.didItemClick(item:)), for: .touchUpInside)
//            }
            
            
            if i == 0  {
                self.didItemClick(item: itemView)
            }
            
        }
        
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //点击单个标签视图，通过currentSelectState的属性观察器更新标签的显示
    //并且通过代理方法切换标签控制器的当前视图控制器
    @objc func didItemClick(item : FGTabBarItem){
        for i in 0..<itemArray.count{
            let tempItem = itemArray[i]
            if i == item.tag{
                tempItem.currentSelectState = true
            }else{
                tempItem.currentSelectState = false
            }
        }
        //执行代理方法
        self.delegate?.didSelectItem(itemIndex: item.tag)
    }
    
    @objc func didClickMid(item : FGTabBarItem) {
        self.delegate?.didSelectMid()
    }

}
